<?php
namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Tymon\JWTAuth\Facades\JWTAuth;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected function response($data = '', $status = 200, $headers = [])
    {
        return response()->json($data, $status, $headers);
    }

    protected function error($msg = '', $status = 400)
    {
        $headers = ['Content-Type' => 'application/json'];
        return $this->response($msg, $status, $headers);
    }

    protected function warning($msg, $url = false)
    {
        $url = $url ?: HTTP_REFERER;
        $data = compact('msg', 'url');
        return view('common/warning', $data);
    }

    protected function uploadPic($file){
        if ($file->isValid()) {
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = strtolower($file->getClientOriginalExtension());     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg
            // 上传文件
            if ($ext === false) {
                return ['code'=>false,'data'=>'无效的图片文件'];
            }
            if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
                return ['code'=>false,'data'=>'无效的图片格式'];
            }

            $target_path = 'upload/box/' . date('Y/md');
            $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
            $targetPath = public_path() . DIRECTORY_SEPARATOR . $target_path;
            if (!is_dir($targetPath)) {
                if (!mkdir($targetPath, 0777, 1)) {
                    return ['code'=>false,'data'=>'无效的图片格式'];
                }
            }
            if($file->move($target_path,$filename)){
                return ['code'=>true,'data'=>$target_path.DIRECTORY_SEPARATOR.$filename];
            }else{
                return ['code'=>false,'data'=>'上传失败'];
            }
        }else{
            return ['code'=>false,'data'=>'上传失败'];
        }
    }

    public function JwtChecking($request)
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            $user = false;
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            $user = false;
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            $user = false;
        }
        return $user;
    }
}
